package com.macro.cloud.userservice.controller;

import com.macro.cloud.userservice.result.CommonResult;
import com.macro.cloud.userservice.result.User;
import com.macro.cloud.userservice.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    /**
     * 新建一个用户
     * @param user
     * @return
     */
    @PostMapping("/create")
    public CommonResult<User> create(@RequestBody User user){
        userService.create(user);
        return new CommonResult("操作成功", 200);
    }

    /**
     * 根据id查找用户信息
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public CommonResult<User> getUser(@PathVariable Long id){
        User user = userService.getUser(id);
        logger.info("根据id获取用户信息，用户名称为：{}",user.getUsername());
        return new CommonResult<>(user);
    }

    /**
     * 根据多个id查询多个用户
     * @param ids
     * @return
     */
    @GetMapping("/getUserByIds")
    public CommonResult<List<User>> getUserByIds(@PathVariable List<Long> ids){
        List<User> userByIds = userService.getUserByIds(ids);
        logger.info("根据ids获取用户信息，用户列表为：{}",userByIds);
        return new CommonResult<>(userByIds);
    }

    /**
     * 根据名字查询
     * @param username
     * @return
     */
    @GetMapping("/getByUsername")
    public CommonResult<User> getUserByName(@RequestParam String username){
        User user = userService.getUserByName(username);
        return new CommonResult<>(user);
    }

    /**
     * 更新用户
     * @param user
     * @return
     */
    @PostMapping("/update")
    public CommonResult update(@RequestBody User user){
        userService.update(user);
        return new CommonResult("操作成功", 200);
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @PostMapping("/delete/{id}")
    public CommonResult delete(@PathVariable Long id){
        userService.delete(id);
        return new CommonResult("操作成功", 200);
    }
}
